28. Quiz: Table Constraints

Table Constraints

Enter the complete CREATE TABLE command for these updates

QUESTION:

  • The _id column will contain the id for the pet, in ascending order. It should be automatically generated.
  • The pet's breed is optional and should still have a column.
  • The pet's name, gender and weight must have a value. If the person entering data does not have a weight for the pet, a weight of 0 should be used.

SOLUTION:

NOTE: The solutions are expressed in RegEx pattern. Udacity uses these patterns to check the given answer

Notes

  • Format your quiz input like this, with each command on a new line:

CREATE TABLE pets (

YOUR COMMAND HERE,

YOUR COMMAND HERE,

Last command here);

  • Make sure to put each command on a new line, and remove any trailing whitespaces after each line.


Solution Explanation

CREATE TABLE

SQL keywords used to create a new table

pets

Refers to the name of the table to be created

(_id INTEGER PRIMARY KEY AUTOINCREMENT,

The first column of the table will be called id and be of type _INTEGER. Since we want it to be the id for the rows of the table, we use the keyword PRIMARY KEY. To have it automatically increase in ascending order when a new row is created, we use the keyword AUTOINCREMENT.

name TEXT NOT NULL,

The data type of name will be TEXT. We indicate this column must have a value with the keywords NOT NULL.

breed TEXT,

The data type of breed will be TEXT. Because it is optional, we don't need the keywords NOT NULL

gender INTEGER NOT NULL,

The data type of gender will be INTEGER (0 - Unknown, 1 - Male, 2 - Female). We indicate this column must have a value with the keywords NOT NULL.

weight INTEGER NOT NULL DEFAULT 0);

The data type of weight will be INTEGER. We indicate this column must have a value with the keywords NOT NULL. We indicate the default value, if none is provided, will be 0 with DEFAULT 0.


Solution Code

CREATE TABLE pets (

_id INTEGER PRIMARY KEY AUTOINCREMENT,

name TEXT NOT NULL,

breed TEXT,

gender INTEGER NOT NULL,

weight INTEGER NOT NULL DEFAULT 0);